import { goTo } from '@/modules/move'
import { ObserveTask, ObserveTaskCallback, ObserveTaskType } from './types'
import { signController } from './sign'
import { remoteObserve } from '../remoteHarvest'
import { dpHarvestRoomObserver } from '../dpHarvest'

/**
 * 到达房间后执行的回调函数
 */
const callbacks: { [type in ObserveTaskType]: ObserveTaskCallback } = {
    remoteHarvest: remoteObserve,
    sign: signController,
    dpHarvest: dpHarvestRoomObserver,
}

/**
 * scout 工作
 */
export const scoutWork = function (room: MyRoom, task: ObserveTask) {
    if (!task.scouts.length) return

    const { scouts: scoutNames, roomNames } = task

    const scouts = scoutNames.map((name) => Game.creeps[name]).filter(Boolean)

    scouts.forEach((scout) => {
        const roomName = roomNames[task.roomIndex || 0]
        const observedRooms = task.observedRooms || []
        const currentRoom = scout.room.name

        const canObserve = !observedRooms.includes(currentRoom) && roomNames.includes(currentRoom)

        if (scout.room.name !== roomName) {
            goTo(scout, new RoomPosition(25, 25, roomName), { range: 23 })
            if (!canObserve) return
        }

        // 到达房间后就执行指定类型的任务
        const callback = callbacks[task.type]
        if (callback) {
            const next = () => {
                if (task.roomIndex >= roomNames.length - 1) {
                    task.done = true
                    return false
                }

                task.roomIndex = (task.roomIndex || 0) + 1
                return true
            }

            callback(scout, task, next)
            task.observedRooms = Array.from(new Set([...observedRooms, currentRoom]))
        } else {
            task.done = true
            console.log(`[observe] 未知的任务类型 ${task.type}`)
        }
    })
}
